package helper;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
//import java.lang.System.Logger;
import java.net.URL;
import java.net.URLConnection;
//import java.nio.charset.StandardCharsets;
//import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import helper.LogHelper;

//import javax.swing.text.StyleConstants.CharacterConstants;
//
//import util.Constants;

public class WebHelper {
	private static LogHelper logger = new LogHelper();
	/**
	 * 得到刷新令牌头部
	 * @param companyNo 公司编号
	 * @param loginName 登录名
	 * @param privateKey 私钥
	 * */
	public static HashMap<String, String> GetTokenHeaders(String companyNo, String loginName, String privateKey) {
		String dateFormatString = "YYYY-MM-DD HH:mm:ss";
		String timeStamp = DateTimeHelper.str2TimeStampMillions(DateTimeHelper.GetDateTime(dateFormatString), dateFormatString).toString();
		String nonce = UUID.randomUUID().toString();
		
		HashMap<String, String> parameterMap = new HashMap<String, String>();
		parameterMap.put("timestamp", timeStamp);
		parameterMap.put("nonce", nonce);
		parameterMap.put("companyNo", companyNo);
		parameterMap.put("loginName", loginName);
		
		String data = SignatureHelper.GetSignatureContent(parameterMap);
		String signature = SignatureHelper.Sign(data, privateKey);
		
		HashMap<String, String> headers = new HashMap<String, String>();
		headers.put("timestamp", timeStamp);
		headers.put("nonce", nonce);
		headers.put("companyNo", companyNo);
		headers.put("loginName", loginName);
		headers.put("signature", signature);
		return headers;
	}
	/**
	 * 得到查询签名头部
	 * @param companyNo 公司编号
	 * @param loginName 登录名
	 * @param privateKey 私钥
	 * @throws NoSuchAlgorithmException 
	 * */
	public static HashMap<String, String> GetHeaders(String companyNo, String token) throws NoSuchAlgorithmException {
		String dateFormatString = "YYYY-MM-DD HH:mm:ss";
		String timeStamp = DateTimeHelper.str2TimeStampMillions(DateTimeHelper.GetDateTime(dateFormatString), dateFormatString).toString();
		String nonce = UUID.randomUUID().toString();
		
		HashMap<String, String> parameterMap = new HashMap<String, String>();
		parameterMap.put("timestamp", timeStamp);
		parameterMap.put("nonce", nonce);
		parameterMap.put("companyNo", companyNo);
		parameterMap.put("token", token);
		
		String data = SignatureHelper.GetSignatureContent(parameterMap);
		String signature = SecurityHelper.MD5(data, "utf-8");
		
		HashMap<String, String> headers = new HashMap<String, String>();
		headers.put("timestamp", timeStamp);
		headers.put("nonce", nonce);
		headers.put("companyNo", companyNo);
		headers.put("token", token);
		headers.put("signature", signature);
		
		return headers;
	}
	/**
	 * 得到 Post、Put、Delete 请求头部
	 * @param companyNo 公司编号
	 * @param token 令牌
	 * @param privateKey 私钥
	 * @param params 被提交的数据
	 * */
	public static HashMap<String, String> GetHeaders(String companyNo, String token, String params) throws NoSuchAlgorithmException {
		String dateFormatString = "YYYY-MM-DD HH:mm:ss";
		String timeStamp = DateTimeHelper.str2TimeStampMillions(DateTimeHelper.GetDateTime(dateFormatString), dateFormatString).toString();
		String nonce = UUID.randomUUID().toString();
		
		HashMap<String, String> parameterMap = new HashMap<String, String>();
		parameterMap.put("timestamp", timeStamp);
		parameterMap.put("nonce", nonce);
		parameterMap.put("companyNo", companyNo);
		parameterMap.put("token", token);
		if(params != null && params != "") {
			parameterMap.put("data", params);
		}
		String data = SignatureHelper.GetSignatureContent(parameterMap);
		String signature = SecurityHelper.MD5(data, "utf-8");
//		logger.Debug(WebHelper.class.getName() + ".GetHeaders", "\n" + data + "\nsignature = " + signature);
		parameterMap.put("signature", signature);
		return parameterMap;
	}
	/**
	 * 向指定的 URL   发送GET请求
	 * @param url   发送请求的 URL
	 * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式
	 * @return 远程响应结果
	 * */
	public static String SendGet(String url, String param, HashMap<String, String> headers) {
		StringBuilder result = new StringBuilder();
		BufferedReader in = null;
		try {
			if(param != null && param != "") {
				url += "?" + param;
			}
			URL realUrl = new URL(url);
			URLConnection connection = realUrl.openConnection();
			connection.setRequestProperty("accept", "application/json");
			connection.setRequestProperty("connection", "Keep-Alive");
			
			if(headers != null) {
				Iterator<String> iterator = headers.keySet().iterator();
				while(iterator.hasNext()) {
					String key = (String)iterator.next();
					String value = headers.get(key);
					connection.addRequestProperty(key, value);
				}
			}
			
			connection.connect();
			// 定义 BufferedReader 输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while((line = in.readLine())!=null) {
				result.append(line);
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			try {
				if(in != null) {
					in.close();
				}
			}catch (Exception ex) {
				// TODO: handle exception
				ex.printStackTrace();
			}
		}
		return result.toString();
	}
	/**
	 * 向指定的 URL   发送POST请求
	 * @param url   发送请求的 URL
	 * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式
	 * @return 远程响应结果
	 * */
	public static String SendPost (String url, String data, HashMap<String, String> headers) {
		StringBuilder result = new StringBuilder();
		BufferedReader buffer = null;
		try {
			URL realUrl = new URL(url);
			URLConnection connection = realUrl.openConnection();
			connection.setConnectTimeout(6 * 1000);
			connection.setReadTimeout(6 * 1000);
			connection.setRequestProperty("accept", "application/json");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("Accept-Charset", "utf-8");
			connection.setRequestProperty("content-Type", "application/json; charset=UTF-8");
			connection.setDoOutput(true); // 设置是否向 httpUrlConnection 输出，因为这个是post请求，参数要放在http正文内，因此需要设置为true，默认情况下位false
			connection.setDoInput(true); // 设置是否从 httpUrlConnection 读入，默认情况下是true;
			connection.setUseCaches(false); // Post 请求不能使用缓存
			
//			String headersStr = JsonHelper.convertFromObjecttoJson(headers);
//			logger.Debug(WebHelper.class.getName() + ".SendPost", "headers = " + headersStr);
			
			if(headers != null) {
				Iterator<String> iterator = headers.keySet().iterator();
				while(iterator.hasNext()) {
					String key = (String)iterator.next();
					String value = headers.get(key);
					connection.addRequestProperty(key, value);
				}
			}
			
			OutputStream outputStream = connection.getOutputStream();
			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "utf-8");
			outputStreamWriter.write(data);
//			logger.Debug(WebHelper.class.getName() + ".SendPost", "ApiRequest<SendSmsApi> request = " + data);
			outputStreamWriter.flush();
			outputStreamWriter.close();
			
			InputStream inputStream = connection.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); // 定义 BufferedReader 输入流来读取URL的响应
			buffer = new BufferedReader(inputStreamReader);
			
			String line;
			while((line = buffer.readLine())!=null) {
				result.append(line);
			}
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			try {
				if(buffer != null) {
					buffer.close();
				}
			}catch (Exception ex) {
				// TODO: handle exception
				ex.printStackTrace();
			}
		}
		return result.toString();
	}
	
	
}
